from .Session import Session
from .functions import *
import redis

class FingerHelper(object):
	"""docstring for FingerHelper"""
	def __init__(self):
		super(FingerHelper, self).__init__()
		self.session = Session()
	
	def connect(self,
			port = "/dev/tty.SLAB_USBtoUART",
			baudrate = 115200,
			timeout = None):
		self.session.connect(port = port, baudrate = baudrate, timeout = timeout)

	def connectDB(self,
			host = "localhost",
			port = 6379,
			db = 0,
			password = None):
		self.db = redis.StrictRedis(host=host, port=port, db=db, password = password)

	def clearFinger(self):
		return self.session.deleteChar()

	def registerFinger(self,
			textAskName = "Please input your name: ",
			textAskPush = "Please put you finger on the scanner.",
			textAskRemove = "Finger scan completed. Please remove your finger.",
			textTellOk = "Register completed!",
			textTellFail = "Register faild!",
			callback = None):
		name = raw_input(textAskName)
		existTplId = self.db.get("finger:template:" + name)
		if existTplId: 
			# self.db.delete("finger:template:" + name)
			# self.db.delete("finger:template:" + existTplId)
			existTplId = int(existTplId)
			# if self.session.deleteChar(existTplId, existTplId) == None:
			# 	print(textTellFail)
			# 	return
		else: existTplId = None

		for i in range(0, 2):
			print(textAskPush)
			while True:
				if self.session.detectFinger():
					if self.session.saveImage():
						if self.session.generateTemplate(i):
							print(textAskRemove)
						else:
							print(textTellFail)
							return False
					else:
						print(textTellFail)
						return False
					break
				else:
					continue
			while True:
				if self.session.detectFinger():
					continue
				else:
					break
		if not self.session.mergeTemplate(count = 2):
			print(textTellFail)
			return False
		storeTplId = self.session.storeChar()
		if storeTplId == None: 
			print(textTellFail)
			return False
		print("storeTplId: ", storeTplId)
		# print(self.session.uploadChar())
		# if existTplId != storeTplId: self.session.deleteChar(existTplId, existTplId)
		self.db.set("finger:template:" + str(storeTplId), name)
		self.db.set("finger:template:" + name, storeTplId)
		if callback: callback(name, storeTplId)
		print(textTellOk)
		return True

	def searchFinger(self,
			textAskPush = "Please put you finger on the scanner.",
			textTellHello = "Hello! ",
			textTellNotFound = "Sorry. I can't find you!",
			textTellError = "System error!"):
		print(textAskPush)
		while True:
			if not self.session.detectFinger():
				continue
			if self.session.saveImage():
				if self.session.generateTemplate():
					tplId = self.session.searchChar()
					if tplId == None: 
						print(textTellNotFound)
						return None
					else:
						name = self.db.get("finger:template:" + str(tplId))
						if name:
							print(textTellHello, name)
							return name
						else:
							print(textTellNotFound)
							return None
				else:
					print(textTellError)
					return None
			else:
				print(textTellError)
				return None

	def matchFinger(self,
			name = "",
			textAskPush = "Please put you finger on the scanner.",
			textTellHello = "Welcome!",
			textTellNotFound = "Sorry. You are not authorized!",
			textTellFail = "System Error!"):
		tplId = self.db.get("finger:template:" + name)
		if tplId:
			tplId = int(tplId)
		else:
			print(textTellFail)
			return False

		if not self.session.loadChar(templateId = tplId, ramId = 1):
			print(textTellFail)
			return False
		print(textAskPush)
		while True:
			if not self.session.detectFinger():
				continue
			if self.session.saveImage():
				if self.session.generateTemplate(ramId = 0):
					if self.session.matchChar(): 
						print(textTellHello)
						return True
					else:
						print(textTellNotFound)
						return False
				else:
					print(textTellFail)
					return False
			else:
				print(textTellFail)
				return False